<template>
  <div class="execution">
    <basic-container>
      <avue-crud ref="crud"
                 :page="page"
                 :data="tableData"
                 :table-loading="tableLoading"
                 :option="tableOption"
                 :before-open="handleOpenBefore"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @row-update="handleUpdate"
                 @row-save="handleSave"
                 @row-del="rowDel">
        <template slot="menuLeft">
          <el-button type="primary"
                     @click="handleAdd"
                     size="small">新 增
          </el-button>
          <br/><br/>
        </template>
        <template slot-scope="scope"
                  slot="menu">
          <el-button type="text"
                     icon="el-icon-plus"
                     size="small"
                     plain
                     @click="handleViewParamsListDialog(scope.row,scope.index)">参数列表
          </el-button>
          <el-button type="text"
                     icon="el-icon-check"
                     size="small"
                     plain
                     @click="handleEdit(scope.row,scope.index)">编辑
          </el-button>
          <el-button type="text"
                     icon="el-icon-delete"
                     size="small"
                     plain
                     @click="handleDel(scope.row,scope.index)">删除
          </el-button>
        </template>
        <template slot="shopNameForm"
                  slot-scope="scope">
          <avue-crud-select v-model="shopId"
                            @change="handlerShopsChange"
                            placeholder="请选择商铺"
                            :dic="shopsOptions"
                            :props="shopsProps"></avue-crud-select>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog :title="dialogStatus=='create'?'添加参数':'更新参数'" :visible.sync="addParamsDialogVisible" width="36%">
      <el-form :model="paramsForm" :rules="dataRule" ref="dataForm" label-width="80px" size="small">
        <el-form-item label="标签名" prop="label">
          <el-input v-model="paramsForm.label"></el-input>
        </el-form-item>
        <el-form-item label="参数值" prop="value">
<!--          <el-input v-model="paramsForm.value"></el-input>-->
          <el-input-number v-model="paramsForm.value" @change="handleParamValueChange" :min="1" :max="1000" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="paramsForm.sort" type="number"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow">
          <el-radio-group v-model="paramsForm.isShow">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
          :action="actionUrl"
          :headers="headers"
          :limit="1"
          :file-list="fileList"
          list-type="picture-card"
          :on-success="handleUploadSuccess"
          :on-remove="handleImageRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button size="small" v-if="dialogStatus=='create'" type="primary" @click="handleAddParams">保 存</el-button>
        <el-button size="small" v-if="dialogStatus=='update'" type="primary" @click="handleUpdateParams">更 新</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="参数列表"
      :visible.sync="paramsListVisible"
      :before-close="handleClose">
      <el-button type="primary"
                 icon="el-icon-plus"
                 size="small"
                 plain
                 @click="handleAddParamsDialog()">添加参数
      </el-button>
      <el-table
        :data="paramsList"
        height="500"
        style="width: 100%">
        <el-table-column
          prop="label"
          label="标签名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="value"
          label="值"
          width="180">
        </el-table-column>
        <el-table-column
          prop="image"
          label="图片"
          width="180">
          <template slot-scope="scope">
            <img v-if="scope.row.image" width="100" height="100" :src="scope.row.image">
          </template>
        </el-table-column>
        <el-table-column
          prop="isShow"
          label="是否显示"
          width="180">
        </el-table-column>
        <el-table-column
          prop="sort"
          label="排序">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="100">
          <template slot-scope="scope">
            <el-button @click="handleDelParams(scope.row, scope.$index)" type="text" size="small">删除</el-button>
            <el-button @click="handlerEditParams(scope.row, scope.$index)" type="text" size="small">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>

  </div>
</template>

<script>
  import Vue from 'vue'
  // import store from "@/store";
  import {handleImgUrl} from '@/utils/util'
  import {fetchList, getObj, addObj, putObj, delObj} from '@/api/merchantservices/collocationtype'
  import {fetchParamsList, getParamsObj, addParamsObj, putParamsObj, delParamsObj, getParamsList} from '@/api/merchantservices/collocationtypeproperty'
  import {tableOption} from '@/const/crud/merchantservices/collocationtype'
  import {mapGetters} from 'vuex'
  import {getAllShops} from '@/api/shop/shops'

  export default {
    name: 'collocationtype',
    data() {
      return {
        headers: {
          'token': Vue.cookie.get('token')
        },
        dialogStatus: 'create',
        fileList: [],
        actionUrl:'',
        tableData: [],
        paramsList: [], //参数列表
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,
        addParamsDialogVisible: false,
        paramsListVisible: false,
        paramsForm: {
          isShow: 1,
          sort: 100,
          value: '',
          image: '',
          collTypeId: '',
          label: ''
        },
        shopsProps: {
          label: "shopName",
          value: 'id'
        },
        shopsOptions: [],
        shopId: '',
        dataRule: {
          label: [
            { required: true, message: '标签名不能为空', trigger: 'blur' }
          ],
          value: [
            { required: true, message: '值不能为空', trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '排序不能为空', trigger: 'blur' }
          ],
          isShow: [
            { required: true, message: '是否显示不能为空', trigger: 'change' }
          ]
        }
      }
    },
    created() {
    },
    mounted: function () {
      this.actionUrl = this.$http.adornUploadUrl()
      this.getList(this.page)
    },
    // computed: {
    //   ...mapGetters(['permissions'])
    // },
    watch: {
      shopName() {
        this.form.shopName = this.shopName
      }
    },
    methods: {
      getAllShops() {
        const data = new FormData()
        data.append('shopId',this.$store.state.user.shopId)
        getAllShops(data)
          .then((res) => {
            this.shopsOptions = res.data.data
          })
      },
      getList(page, params) {
        this.tableLoading = true
        fetchList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params)).then(response => {
          this.tableData = response.data.data.records
          this.page.total = response.data.data.total
          this.tableLoading = false
        })
      },
      /**
       * @title 打开新增窗口
       * @detail 调用crud的handleadd方法即可
       *
       **/
      handleAdd: function () {
        this.$refs.crud.rowAdd()
      },
      handleEdit(row, index) {
        this.$refs.crud.rowEdit(row, index)
      },
      handleDel(row, index) {
        this.$refs.crud.rowDel(row, index)
      },
      rowDel: function (row, index) {
        var _this = this
        this.$confirm('是否确认删除ID为' + row.id, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delObj(row.id)
        }).then(data => {
          _this.tableData.splice(index, 1)
          _this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
          this.getList(this.page)
        }).catch(function (err) {
        })
      },
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate: function (row, index, done) {
        putObj(row).then(data => {
          this.tableData.splice(index, 1, Object.assign({}, row))
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          })
          done()
          this.getList(this.page)
        })
      },
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave: function (row, done) {
        addObj(row).then(data => {
          this.tableData.push(Object.assign({}, row))
          this.$message({
            showClose: true,
            message: '添加成功',
            type: 'success'
          })
          done()
          this.getList(this.page)
        })
      },
      /**
       * 刷新回调
       */
      refreshChange() {
        this.getList(this.page)
      },
      /**
       * 打开添加参数对话框
       */
      handleAddParamsDialog() {
        this.addParamsDialogVisible = true
        this.dialogStatus = 'create'
        this.fileList = []
        this.paramsForm.image = ''
      },
      //添加参数
      handleAddParams() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addParamsObj(this.paramsForm).then(res => {
              this.$refs['dataForm'].resetFields()
              this.addParamsDialogVisible = false
              this.$message({
                showClose: true,
                message: '添加成功',
                 type: 'success'
              })
              this.getParamsList(this.paramsForm.collTypeId)
            })
          }
        })
      },
      //更新参数
      handleUpdateParams() {
        putParamsObj(this.paramsForm)
          .then(res => {
            let collTypeId = this.paramsForm.collTypeId
            this.$refs['dataForm'].resetFields()
            this.addParamsDialogVisible = false
            this.$message({
              showClose: true,
              message: '更新成功',
              type: 'success'
            })
            this.getParamsList(collTypeId)
          })
      },
      /**
       *查看参数列表对话框
       */
      handleViewParamsListDialog(row, index) {
        this.getParamsList(row.id)
        this.paramsForm.collTypeId = row.id
        this.paramsListVisible = true
      },

      /**
       * 获取参数列表
       */
      getParamsList(typeId) {
        let formData = new FormData()
        formData.append('typeId', typeId)
        getParamsList(formData)
          .then(res => {
            this.paramsList = res.data.data
          })
      },


      handleClose() {
        this.paramsListVisible = false
        this.addParamsDialogVisible = false
        this.paramsForm = {
          isShow: 1,
          sort: 100,
          value: '',
          image: '',
          collTypeId: '',
          label: ''
        }
      },
      /**
       * 删除参数
       */
      handleDelParams(row, index) {
        let _this = this
        this.$confirm('是否确认删除ID为' + row.id, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delParamsObj(row.id)
        }).then(data => {
          _this.paramsList.splice(index, 1)
          _this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
          this.getParamsList(row.collTypeId)
        }).catch(function (err) {
        })
      },
      handleUploadSuccess(res, file) {
        this.paramsForm.image = res.data.bucketName + "-" + res.data.fileName;
      },
      handleImageRemove() {
        this.paramsForm.image = ''
      },

      /**
       * 修改参数
       */
      handlerEditParams(row, index) {
        this.addParamsDialogVisible = true
        this.dialogStatus = 'update'
        getParamsObj(row.id)
          .then(res => {
            if (res.data.code === 0) {
              let data = res.data.data
              this.paramsForm.collTypeId = data.collTypeId
              this.paramsForm.image = data.image
              if (this.paramsForm.image) {
                handleImgUrl(this.paramsForm.image).then((res) => {
                  this.fileList = [{
                    url: res.data
                  }]
                })
              } else {
                this.fileList = []
              }
              this.paramsForm.id = data.id
              this.paramsForm.isShow = data.isShow
              this.paramsForm.sort = data.sort
              this.paramsForm.value = data.value
              this.paramsForm.label = data.label
            } else {
              this.$message.error('获取失败')
            }
          })
      },
      handleOpenBefore(show, type) {
        this.shopId = ''
        this.getAllShops()
        show()
      },
      handlerShopsChange(value) {
        for (let i = 0; i < this.shopsOptions.length; i++) {
          if (this.shopsOptions[i].id === value) {
            this.shopName = this.shopsOptions[i].shopName
          }
        }
      },
      handleParamValueChange(val) {
        // console.log(val)
      },
      currentChange(val) {
        this.page.currentPage = val
        this.getList(this.page)
      },
      sizeChange(val) {
        this.page.currentPage = 1
        this.page.pageSize = val
        this.getList(this.page)
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
